package com.cskaoyan.service;

import com.cskaoyan.bean.entity.Aftersale;
import com.cskaoyan.bean.entity.AftersaleExample;
import com.cskaoyan.bean.vo.BasePageData;
import com.cskaoyan.bean.vo.BaseParam;
import com.cskaoyan.mapper.AftersaleMapper;
import com.cskaoyan.mapper.OrderMapper;
import com.cskaoyan.utils.AftersaleStatus;
import com.cskaoyan.utils.Constant;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author break_a_leg
 * @description
 * @date 2021年10月18日 20:54
 */
@Service
public class AftersaleServiceImpl implements AftersaleService {

    @Autowired
    AftersaleMapper aftersaleMapper;

    @Autowired
    OrderMapper orderMapper;

    @Override
    public BasePageData query(Short status, String aftersaleSn, Integer orderId, BaseParam param) {
        // 配置分页信息
        PageHelper.startPage(param.getPage(),param.getLimit());
        AftersaleExample aftersaleExample = new AftersaleExample();
        AftersaleExample.Criteria criteria = aftersaleExample.createCriteria();
        if (!StringUtils.isEmpty(aftersaleSn)) {
            criteria.andAftersaleSnEqualTo(aftersaleSn);
        }
        if (orderId != null) {
            criteria.andOrderIdEqualTo(orderId);
        }
        if (status != null) {
            if (status == 1) {
                criteria.andStatusEqualTo(((short) 1));
            } else if (status == 2) {
                criteria.andStatusEqualTo(((short) 2));
            } else {
                criteria.andStatusEqualTo(null);
            }
        }
        criteria.andDeletedEqualTo(false);
        // 设置排序
        aftersaleExample.setOrderByClause(param.getSort() + " " + param.getOrder());
        List<Aftersale> aftersales = aftersaleMapper.selectByExample(aftersaleExample);
        return BasePageData.ok(aftersales);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int update(Integer[] ids, Integer modifyCode, Integer originalCode) {
        int count = 0;
        for (Integer id : ids) {
            // 通过  修改status为1的变为2
            int affectedRows = aftersaleMapper.updateStatusById(id,modifyCode,originalCode);
            count = count + affectedRows;
            if (affectedRows == 1) {
                //查询通过的售后订单的order_id  去修改订单表的aftersale_status
                Integer orderId = aftersaleMapper.selectOrderIdByAftersaleId(id);
                orderMapper.updateStatusByOrderId(modifyCode,orderId);
            }
        }
        if (count == 0) {
            return Constant.FAIL;
        }
        return Constant.SUCCESS;
    }
}
